//! # 性能模块综合测试
//! 
//! 提供性能模块的全面测试覆盖，包括单元测试、集成测试和性能测试。

use crate::performance::connection::*;
use crate::performance::memory::*;
use crate::performance::async_pool::*;
use crate::performance::config::*;
use crate::performance::traits::*;
use rustcloud_core::{ServiceResult, ServiceError};
use std::sync::Arc;
use std::collections::HashMap;
use tokio::sync::RwLock;
use async_trait::async_trait;
use std::sync::atomic::{AtomicU32, AtomicBool, Ordering};
use std::time::Duration;

/// 模拟连接
#[derive(Debug, Clone)]
pub struct MockConnection {
    pub id: String,
    is_valid: Arc<AtomicBool>,
}

impl MockConnection {
    pub fn new(id: String) -> Self {
        Self {
            id,
            is_valid: Arc::new(AtomicBool::new(true)),
        }
    }

    pub fn set_invalid(&self) {
        self.is_valid.store(false, Ordering::Relaxed);
    }

    pub fn is_valid(&self) -> bool {
        self.is_valid.load(Ordering::Relaxed)
    }
}

/// 模拟连接工厂
pub struct MockConnectionFactory {
    should_fail: Arc<AtomicBool>,
    connection_counter: Arc<AtomicU32>,
}

impl MockConnectionFactory {
    pub fn new() -> Self {
        Self {
            should_fail: Arc::new(AtomicBool::new(false)),
            connection_counter: Arc::new(AtomicU32::new(0)),
        }
    }

    pub fn set_should_fail(&self, fail: bool) {
        self.should_fail.store(fail, Ordering::Relaxed);
    }
}

#[async_trait]
impl ConnectionFactory<MockConnection> for MockConnectionFactory {
    async fn create_connection(&self) -> ServiceResult<MockConnection> {
        if self.should_fail.load(Ordering::Relaxed) {
            return Err(ServiceError::InternalError("模拟连接创建失败".to_string()));
        }

        let id = self.connection_counter.fetch_add(1, Ordering::Relaxed);
        Ok(MockConnection::new(format!("mock_conn_{}", id)))
    }

    async fn validate_connection(&self, connection: &MockConnection) -> bool {
        connection.is_valid()
    }

    async fn destroy_connection(&self, _connection: MockConnection) -> ServiceResult<()> {
        // 模拟连接销毁
        tracing::debug!("销毁模拟连接");
        Ok(())
    }

    fn connection_type(&self) -> &str {
        "MockConnection"
    }
}

/// 测试连接池基本操作
#[tokio::test]
async fn test_connection_pool_basic_operations() {
    let config = ConnectionPoolConfig::default();
    let factory = Arc::new(MockConnectionFactory::new());
    let pool = GenericConnectionPool::new(config, factory.clone());

    // 初始化连接池
    pool.initialize().await.unwrap();

    // 获取连接
    let conn = pool.acquire().await.unwrap();
    assert_eq!(conn.connection.id, "mock_conn_0");
    assert_eq!(conn.state, ConnectionState::Active);

    // 验证统计信息
    let stats = pool.get_stats().await;
    assert_eq!(stats.active_connections, 1);
    assert_eq!(stats.acquire_count, 1);

    // 释放连接
    pool.release(&conn.id).await.unwrap();

    let stats = pool.get_stats().await;
    assert_eq!(stats.active_connections, 0);
    assert_eq!(stats.release_count, 1);
    assert_eq!(stats.idle_connections, 1);

    // 关闭连接池
    pool.shutdown().await.unwrap();
}

/// 测试连接验证功能
#[tokio::test]
async fn test_connection_validation() {
    let config = ConnectionPoolConfig::default();
    let factory = Arc::new(MockConnectionFactory::new());
    let pool = GenericConnectionPool::new(config, factory.clone());

    pool.initialize().await.unwrap();

    // 获取连接
    let conn = pool.acquire().await.unwrap();
    
    // 验证有效连接
    let is_valid = pool.validate_connection(&conn.id).await.unwrap();
    assert!(is_valid);

    // 设置连接为无效
    conn.connection.set_invalid();
    
    // 验证无效连接
    let is_valid = pool.validate_connection(&conn.id).await.unwrap();
    assert!(!is_valid);

    pool.release(&conn.id).await.unwrap();
    pool.shutdown().await.unwrap();
}

/// 测试连接工厂失败场景
#[tokio::test]
async fn test_connection_factory_failure() {
    let config = ConnectionPoolConfig::default();
    let factory = Arc::new(MockConnectionFactory::new());
    let pool = GenericConnectionPool::new(config, factory.clone());

    pool.initialize().await.unwrap();

    // 设置工厂失败
    factory.set_should_fail(true);

    // 尝试获取连接应该失败
    let result = pool.acquire().await;
    assert!(result.is_err());

    pool.shutdown().await.unwrap();
}

/// 测试过期连接清理
#[tokio::test]
async fn test_expired_connection_cleanup() {
    let mut config = ConnectionPoolConfig::default();
    config.idle_timeout_seconds = 0; // 立即过期
    let factory = Arc::new(MockConnectionFactory::new());
    let pool = GenericConnectionPool::new(config, factory.clone());

    pool.initialize().await.unwrap();

    // 获取并释放连接
    let conn = pool.acquire().await.unwrap();
    pool.release(&conn.id).await.unwrap();

    // 清理过期连接
    let cleaned_count = pool.cleanup_expired().await.unwrap();
    assert_eq!(cleaned_count, 1);

    pool.shutdown().await.unwrap();
}

/// 测试内存管理器基本操作
#[tokio::test]
async fn test_memory_manager_basic_operations() {
    let gc_config = GcConfig::default();
    let manager = MemoryManagerImpl::new(gc_config);

    // 创建内存池
    manager.create_pool("test_pool".to_string(), 1024, 100).await.unwrap();

    // 分配内存
    let block = manager.allocate("test_pool").await.unwrap();
    assert_eq!(block.len(), 1024);

    // 验证统计信息
    let stats = manager.get_stats().await;
    assert_eq!(stats.allocation_count, 1);
    assert_eq!(stats.total_allocated, 1024);
    assert_eq!(stats.current_used, 1024);

    // 释放内存
    manager.deallocate("test_pool", block).await.unwrap();

    // 验证统计信息
    let stats = manager.get_stats().await;
    assert_eq!(stats.allocation_count, 1);
    assert_eq!(stats.deallocation_count, 1);
    assert_eq!(stats.current_used, 0);

    // 测试不存在的内存池
    let result = manager.allocate("nonexistent_pool").await;
    assert!(result.is_err());
}

/// 测试内存管理器垃圾回收
#[tokio::test]
async fn test_memory_manager_garbage_collection() {
    let gc_config = GcConfig::default();
    let manager = MemoryManagerImpl::new(gc_config);

    // 创建内存池
    manager.create_pool("test_pool".to_string(), 512, 10).await.unwrap();

    // 分配多个块
    let mut blocks = Vec::new();
    for _ in 0..5 {
        let block = manager.allocate("test_pool").await.unwrap();
        blocks.push(block);
    }

    // 验证分配统计
    let stats = manager.get_stats().await;
    assert_eq!(stats.allocation_count, 5);
    assert_eq!(stats.current_used, 2560); // 5 * 512

    // 释放所有块
    for block in blocks {
        manager.deallocate("test_pool", block).await.unwrap();
    }

    // 验证释放统计
    let stats = manager.get_stats().await;
    assert_eq!(stats.deallocation_count, 5);
    assert_eq!(stats.current_used, 0);

    // 执行垃圾回收
    let freed = manager.garbage_collect().await.unwrap();
    assert!(freed > 0); // 应该释放了一些内存块
}

/// 测试异步任务池基本操作
#[tokio::test]
async fn test_async_task_pool_basic_operations() {
    let pool = AsyncTaskPoolImpl::new(4);

    let counter = Arc::new(AtomicU32::new(0));
    let counter_clone = counter.clone();

    // 提交任务
    pool.submit(move || {
        counter_clone.fetch_add(1, Ordering::Relaxed);
    }).await.unwrap();

    // 等待任务执行
    tokio::time::sleep(Duration::from_millis(50)).await;

    assert_eq!(counter.load(Ordering::Relaxed), 1);

    // 验证统计信息
    let stats = pool.get_stats().await;
    assert_eq!(stats.submitted_tasks, 1);
    assert_eq!(stats.completed_tasks, 1);
    assert_eq!(stats.worker_count, 4);

    // 关闭任务池
    pool.shutdown().await.unwrap();
}

/// 测试异步任务池异步任务
#[tokio::test]
async fn test_async_task_pool_with_async_tasks() {
    let pool = AsyncTaskPoolImpl::new(2);

    // 提交异步任务
    let handle = pool.submit_async(async {
        tokio::time::sleep(Duration::from_millis(10)).await;
        42
    }).await.unwrap();

    // 等待任务完成并获取结果
    let result = handle.await.unwrap();
    assert_eq!(result, 42);

    // 验证统计信息
    let stats = pool.get_stats().await;
    assert_eq!(stats.submitted_tasks, 1);
    assert_eq!(stats.completed_tasks, 1);

    pool.shutdown().await.unwrap();
}

/// 测试连接池构建器
#[tokio::test]
async fn test_connection_pool_builder() {
    let factory = MockConnectionFactory::new();
    let pool = ConnectionPoolBuilder::new()
        .max_connections(200)
        .min_connections(20)
        .connection_timeout(60)
        .idle_timeout(600)
        .validation_enabled(true)
        .with_factory(factory)
        .build()
        .unwrap();

    // 验证配置
    // 注意：由于GenericConnectionPool内部存储的是ConnectionPoolConfig，
    // 我们无法直接访问这些值进行验证，但构建过程应该成功
    assert!(true); // 构建成功即为通过
}

/// 测试内存管理器构建器
#[tokio::test]
async fn test_memory_manager_builder() {
    let manager = MemoryManagerBuilder::new()
        .auto_gc_enabled(true)
        .gc_threshold(0.7)
        .gc_interval(Duration::from_secs(15))
        .pressure_threshold(0.95)
        .build();

    let stats = manager.get_stats().await;
    assert_eq!(stats.pool_count, 0);
    assert_eq!(stats.allocation_count, 0);
}

/// 测试异步任务池构建器
#[tokio::test]
async fn test_async_task_pool_builder() {
    let pool = AsyncTaskPoolBuilder::new()
        .worker_count(6)
        .build();

    let stats = pool.get_stats().await;
    assert_eq!(stats.worker_count, 6);

    pool.shutdown().await.unwrap();
}

/// 测试性能配置验证
#[test]
fn test_performance_config_validation() {
    // 测试有效的连接池配置
    let valid_config = ConnectionPoolConfig {
        max_connections: 100,
        min_connections: 10,
        connection_timeout_seconds: 30,
        idle_timeout_seconds: 300,
        validation_interval_seconds: 60,
        validation_enabled: true,
    };
    assert!(valid_config.validate().is_ok());
    
    // 测试无效的连接池配置 - 最大连接数为0
    let invalid_config = ConnectionPoolConfig {
        max_connections: 0,
        ..valid_config.clone()
    };
    assert!(invalid_config.validate().is_err());
    
    // 测试有效的内存配置
    let valid_memory_config = MemoryConfig::default();
    assert!(valid_memory_config.validate().is_ok());
    
    // 测试有效的GC配置
    let valid_gc_config = GcConfig::default();
    assert!(valid_gc_config.validate().is_ok());
    
    // 测试有效的异步任务池配置
    let valid_async_config = AsyncTaskPoolConfig::default();
    assert!(valid_async_config.validate().is_ok());
}

/// 测试性能配置构建器
#[test]
fn test_performance_config_builder() {
    let config = PerformanceConfigBuilder::new()
        .max_connections(200)
        .min_connections(20)
        .connection_timeout(60)
        .core_threads(8)
        .max_threads(16)
        .default_block_size(2048)
        .auto_gc_enabled(false)
        .async_worker_threads(8)
        .build()
        .unwrap();
        
    assert_eq!(config.connection_pool.max_connections, 200);
    assert_eq!(config.connection_pool.min_connections, 20);
    assert_eq!(config.connection_pool.connection_timeout_seconds, 60);
    assert_eq!(config.thread_pool.core_threads, 8);
    assert_eq!(config.thread_pool.max_threads, 16);
    assert_eq!(config.memory.default_block_size, 2048);
    assert!(!config.memory.gc.auto_gc_enabled);
    assert_eq!(config.async_task_pool.worker_threads, 8);
}

/// 测试性能管理器
#[tokio::test]
async fn test_performance_manager() {
    let manager = PerformanceManager::new();
    
    // 验证初始状态
    assert!(manager.connection_pool.is_none());
    assert!(manager.memory_manager.is_none());
    assert!(manager.async_task_pool.is_none());
    
    // 测试统计信息获取（应该返回None）
    assert!(manager.get_connection_pool_stats().await.is_none());
    assert!(manager.get_memory_stats().await.is_none());
    assert!(manager.get_async_pool_stats().await.is_none());
}

/// 测试性能管理器构建器
#[tokio::test]
async fn test_performance_manager_builder() {
    let manager = PerformanceManagerBuilder::new().build();
    
    // 验证初始状态
    assert!(manager.connection_pool.is_none());
    assert!(manager.memory_manager.is_none());
    assert!(manager.async_task_pool.is_none());
}

/// 测试配置Duration助手方法
#[test]
fn test_config_duration_helpers() {
    let config = ConnectionPoolConfig::default();
    assert_eq!(config.connection_timeout(), Duration::from_secs(30));
    assert_eq!(config.idle_timeout(), Duration::from_secs(300));
    assert_eq!(config.validation_interval(), Duration::from_secs(60));
    
    let gc_config = GcConfig::default();
    assert_eq!(gc_config.gc_interval(), Duration::from_secs(30));
}

/// 测试并发连接池操作
#[tokio::test]
async fn test_concurrent_connection_pool_operations() {
    let config = ConnectionPoolConfig::default();
    let factory = Arc::new(MockConnectionFactory::new());
    let pool = Arc::new(GenericConnectionPool::new(config, factory.clone()));
    
    pool.initialize().await.unwrap();
    
    // 并发获取连接
    let mut handles = vec![];
    for i in 0..10 {
        let pool_clone = pool.clone();
        let handle = tokio::spawn(async move {
            let conn = pool_clone.acquire().await.unwrap();
            // 模拟一些工作
            tokio::time::sleep(Duration::from_millis(10)).await;
            pool_clone.release(&conn.id).await.unwrap();
            i
        });
        handles.push(handle);
    }
    
    // 等待所有任务完成
    let results: Result<Vec<_>, _> = futures::future::join_all(handles).await.into_iter().collect();
    assert!(results.is_ok());
    
    // 验证统计信息
    let stats = pool.get_stats().await;
    assert_eq!(stats.acquire_count, 10);
    assert_eq!(stats.release_count, 10);
    
    pool.shutdown().await.unwrap();
}

/// 测试内存池容量限制
#[tokio::test]
async fn test_memory_pool_capacity_limits() {
    let gc_config = GcConfig::default();
    let manager = MemoryManagerImpl::new(gc_config);

    // 创建小容量内存池
    manager.create_pool("small_pool".to_string(), 256, 2).await.unwrap();

    // 分配超过容量的块应该成功（因为我们没有限制已分配数量，只是限制总块数）
    let block1 = manager.allocate("small_pool").await.unwrap();
    let block2 = manager.allocate("small_pool").await.unwrap();
    let block3 = manager.allocate("small_pool").await.unwrap();

    // 释放块
    manager.deallocate("small_pool", block1).await.unwrap();
    manager.deallocate("small_pool", block2).await.unwrap();
    manager.deallocate("small_pool", block3).await.unwrap();
}

/// 测试异步任务池并发提交
#[tokio::test]
async fn test_async_task_pool_concurrent_submission() {
    let pool = AsyncTaskPoolImpl::new(4);
    let counter = Arc::new(AtomicU32::new(0));

    // 并发提交任务
    let mut handles = vec![];
    for i in 0..20 {
        let counter_clone = counter.clone();
        let pool_clone = pool.clone();
        let handle = tokio::spawn(async move {
            pool_clone.submit(move || {
                std::thread::sleep(Duration::from_millis(2));
                counter_clone.fetch_add(i, Ordering::Relaxed);
            }).await.unwrap();
        });
        handles.push(handle);
    }

    // 等待所有提交完成
    for handle in handles {
        handle.await.unwrap();
    }

    // 等待所有任务执行完成
    tokio::time::sleep(Duration::from_millis(100)).await;

    // 验证统计信息
    let stats = pool.get_stats().await;
    assert_eq!(stats.submitted_tasks, 20);
    assert!(stats.completed_tasks >= 15); // 可能还有一些在执行中

    pool.shutdown().await.unwrap();
}

/// 性能基准测试 - 连接池获取和释放
#[tokio::test]
async fn test_connection_pool_performance_benchmark() {
    let config = ConnectionPoolConfig::default();
    let factory = Arc::new(MockConnectionFactory::new());
    let pool = GenericConnectionPool::new(config, factory.clone());
    
    pool.initialize().await.unwrap();
    
    let start_time = std::time::Instant::now();
    let iterations = 1000;
    
    // 执行大量连接获取和释放操作
    for i in 0..iterations {
        let conn = pool.acquire().await.unwrap();
        // 模拟简单的业务操作
        if i % 100 == 0 {
            tokio::task::yield_now().await;
        }
        pool.release(&conn.id).await.unwrap();
    }
    
    let duration = start_time.elapsed();
    let ops_per_sec = iterations as f64 / duration.as_secs_f64();
    
    println!("性能基准测试: {} 次操作耗时 {:?}, 每秒操作数: {:.2}", 
             iterations, duration, ops_per_sec);
    
    // 确保性能在合理范围内（这个阈值可以根据实际需求调整）
    assert!(ops_per_sec > 1000.0, "连接池操作性能低于预期: {} ops/sec", ops_per_sec);
    
    pool.shutdown().await.unwrap();
}

/// 性能基准测试 - 内存分配和释放
#[tokio::test]
async fn test_memory_allocation_performance_benchmark() {
    let gc_config = GcConfig::default();
    let manager = MemoryManagerImpl::new(gc_config);
    
    // 创建内存池
    manager.create_pool("benchmark_pool".to_string(), 1024, 1000).await.unwrap();
    
    let start_time = std::time::Instant::now();
    let iterations = 10000;
    
    // 执行大量内存分配和释放操作
    for _ in 0..iterations {
        let block = manager.allocate("benchmark_pool").await.unwrap();
        manager.deallocate("benchmark_pool", block).await.unwrap();
    }
    
    let duration = start_time.elapsed();
    let ops_per_sec = (iterations * 2) as f64 / duration.as_secs_f64(); // 乘以2因为每次迭代都有分配和释放
    
    println!("内存分配性能基准测试: {} 次操作耗时 {:?}, 每秒操作数: {:.2}", 
             iterations * 2, duration, ops_per_sec);
    
    // 确保性能在合理范围内
    assert!(ops_per_sec > 50000.0, "内存分配性能低于预期: {} ops/sec", ops_per_sec);
}

/// 测试强制关闭异步任务池
#[tokio::test]
async fn test_force_shutdown() {
    let pool = AsyncTaskPoolImpl::new(2);

    // 提交一个长时间运行的任务
    pool.submit(|| {
        std::thread::sleep(Duration::from_secs(5));
    }).await.unwrap();

    // 强制关闭应该立即返回
    let start = std::time::Instant::now();
    pool.force_shutdown().await.unwrap();
    let duration = start.elapsed();

    assert!(duration < Duration::from_secs(1));
}